<template>
  <div>
    <el-button @click="goAddBanner">添加轮播图</el-button>
  </div>
  <el-table :data="tableData" style="width: 100%">
    <el-table-column prop="bannerid" label="编号" width="150" />

    <el-table-column label="图片" width="120">
      <template #default="scope">
        <img :src="scope.row.img" style="width: 100px; height: 100px" />
      </template>
    </el-table-column>

    <el-table-column label="是否启用" width="120">
      <template #default="scope">
        <el-switch v-model="scope.row.flag" />
      </template>
    </el-table-column>

    <el-table-column prop="link" label="图片连接" width="120" />
    <el-table-column prop="alt" label="图片提示" width="600" />

    <el-table-column fixed="right" label="操作" width="120">
      <template #default="scope">
        <el-button
          link
          type="primary"
          size="small"
          @click="showEdit(scope.row.bannerid)"
        >
          编辑</el-button
        >
        <el-button
          link
          type="primary"
          size="small"
          @click="removeBanner(scope.row.bannerid)"
          >删除</el-button
        >
      </template>
    </el-table-column>
  </el-table>
  <EditBanner
    :drawer="isShowEdit"
    :bannerid="editBannerid"
    @hideMe="hideEdit"
    @modified="modified"
  ></EditBanner>
</template>
  
  <script lang="ts" setup>
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { getBannerListApi, removeBannerApi } from "@/api/banners";
import type { IBanner } from "@/myTypes";
import EditBanner from "./editBanner.vue";

const tableData = reactive<Array<IBanner>>([]);

//一、 获取轮播图数据
async function getBannerList() {
  const res = await getBannerListApi();
  if (res.data.code === "200") {
    tableData.length = 0;
    tableData.push(...res.data.data);
  }
}

getBannerList();

// 二、去添加
const $router = useRouter();
const goAddBanner = () => {
  $router.replace("AddBanner");
};

// 三、删除轮播图
const removeBanner = (bannerid: string) => {
  ElMessageBox.confirm("亲，您真的要删除吗", "删除提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await removeBannerApi(bannerid);
      if (res.data.code === "200") {
        ElMessage.success("删除成功！");
        // 第一种：重新获取数据：
        // getBannerList();
        // 第二种：删除前端的数据：
        let index = tableData.findIndex((item) => item.bannerid === bannerid);
        tableData.splice(index, 1);
      } else {
        ElMessage.info("删除失败！");
      }
    })
    .catch(() => {});
};

// 四、编辑轮播：
const isShowEdit = ref(false);

// 当前修改的bannerid;
const editBannerid = ref<string>("");

//  显示编辑窗口
const showEdit = (bannerid: string) => {
  editBannerid.value = bannerid;

  isShowEdit.value = true;
};

// 隐藏编辑窗口
const hideEdit = () => {
  isShowEdit.value = false;
};

// 修改完毕后，隐藏窗口，刷新数据
const modified = () => {
  hideEdit();
  getBannerList();
};
</script>
  